﻿#define MOBILE_LOG
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using LitJson;
using System;
using System.Runtime.InteropServices;
using UnityEngine.SceneManagement;

public class GameInfo
{
    public string userToken = "";
    public int gameID = -1;
}

public class OSBridgeManager : MonoSingleton<OSBridgeManager>
{
   //是否是从游戏返回app
    public bool isReturnApp;
#if UNITY_ANDROID
    public UnityEngine.AndroidJavaObject javaObject;
#endif
#if UNITY_IPHONE
    [DllImport("__Internal")]
    private static extern void IOSNativeInitCenter(string callBackGameObject, string callBackFunc);
    [DllImport("__Internal")]
    private static extern void OnBack(int ret);
    [DllImport("__Internal")]
    private static extern void ShowMessage(string message);
#endif
#if UNITY_EDITOR
#endif

    //Delegate for after WWW class Get Successfully
    public delegate void AfterWWWGetHandler(string json);

    //Delegate for after WWW class Post Successfully
    public delegate void AfterWWWPostHandler(string json);

    public GameInfo _gameInfo;
    private string _gameName;

    public string GameName
    {
        get { return _gameName; }
    }

    //体力值是否不足
    private bool isNotPower = false;

    public bool IsNotPower
    {
        get { return isNotPower; }
    }

    


    private string _upLoadUserScoreURL = "http://112.74.34.144:3001/gamecenter/gameover?";
    private string _startGameURL = "http://112.74.34.144:3001/gamecenter/startgame?";

    private void Awake()
    {
        //javaObject.Call("unityInitialized");
#if UNITY_ANDROID && !UNITY_EDITOR
       
        try
        {
             AndroidJavaClass javaClass = new AndroidJavaClass("com.unity3d.player.UnityPlayer");
            javaObject = javaClass.GetStatic<AndroidJavaObject>("currentActivity");
             javaObject.Call("unityInitialized");
        }
        catch 
        {
            
        }
#endif
        
    }
   

    /// <summary>
    /// this function will be call by Android/IOS system to InitGame
    /// </summary>
    /// <param name="json"></param>
    public void InitGame(string json)
    {
        StopAllCoroutines();
        try
        {
            _gameInfo = JsonMapper.ToObject<GameInfo>(json);
            switch (_gameInfo.gameID)
            {
                case 1:
                    _gameName = "DaDiShu";
                    break;
                case 2:
                    _gameName = "QuanMinLiuWan";
                    break;
                case 3:
                    _gameName = "XiaYiBaiCeng";
                    break;
                case 4:
                    _gameName = "ArZhanJi";
                    break;
                case 5:
                    _gameName = "QuanMinLaoYu";
                    break;
                case 6:
                    _gameName = "GaoKongTiaoSan";
                    break;
                case 7:
                    _gameName = "DaGongZhiLv";
                    break;
                case 8:
                    _gameName = "TanXianZhiLv";
                    break;
                case 9:
                    _gameName = "TianKongTanQiu";
                    break;
                case 10:
                    _gameName = "ShuZiTanQiu";
                    break;
                case 11:
                    _gameName = "SuJi";
                    break;
                case 12:
                    _gameName = "ShuiGuoTanQiu";
                    break;
                case 13:
                    _gameName = "DaYuChiXiaoYu";
                    break;
                case 14:
                    _gameName = "ShuZiDuoBiQiu";
                    break;
                case 15:
                    _gameName = "SuSuan";
                    break;
                case 16:
                    _gameName = "BaoShiZhengDuo";
                    break;
                default:
                    LogError("GameID of " + _gameInfo.gameID + " Error!");
                    return;
            }
            EventDispatcher.TriggerEvent("OnInitGame", _gameName);
            //StartGame();
          
        }
        catch (Exception e)
        {
            throw e;
        }
    }

    /// <summary>
    /// this function is used for LogError,if we define #MOBILE_LOG it will Call Anroid/IOS
    /// message to show error
    /// </summary>
    /// <param name="message"></param>
    public void LogError(string message)
    {
        Debug.LogError(message);
#if MOBILE_LOG

#if UNITY_ANDROID && !UNITY_EDITOR
        try
        {
            javaObject.Call("showMessage", message);
        }
        catch
        {
        }
#endif
#if UNITY_IPHONE && !UNITY_EDITOR
        ShowMessage(message);
#endif

#endif
    }

    /// <summary>
    /// this function is used for UploadScore to web server
    /// </summary>
    /// <param name="score"></param>
    public void UpLoadScore(int score)
    {
        string url = _upLoadUserScoreURL + "&token=" + WWW.EscapeURL(_gameInfo.userToken) + "&gameId=" +
                     WWW.EscapeURL(_gameInfo.gameID.ToString()) + "&point=" + WWW.EscapeURL(score.ToString());
       Debug.Log(url);
        StartCoroutine(Get(url, UploadScoreHandler));
    }


    /// <summary>
    /// this fnction should be called when exiting game
    /// </summary>
    /// <param name="isCaught"></param>
    public void OnUnityBack(int isCaught)
    {
#if UNITY_ANDROID && !UNITY_EDITOR
        try
        {
            javaObject.Call("onBack", isCaught);
        }
        catch
        {
           
        }
        
#endif
#if UNITY_IPHONE && !UNITY_EDITOR
        OnBack(isCaught);
#endif
#if UNITY_EDITOR

#endif
    }

    /// <summary>
    ///   this function told the server the game has start
    /// </summary>
    public void StartGame()
    {
        string url = _startGameURL + "&token=" + WWW.EscapeURL(_gameInfo.userToken) + "&gameId=" +
                     WWW.EscapeURL(_gameInfo.gameID.ToString());
        StartCoroutine(Get(url, StartGameHandler));
    }

   
    public void BeforeStartGame()
    {
        string url = _startGameURL + "&token=" + WWW.EscapeURL(_gameInfo.userToken) + "&gameId=" +
                     WWW.EscapeURL(_gameInfo.gameID.ToString());
        StartCoroutine(Get(url, BeforeStartHandler));

       
    }

    private void UploadScoreHandler(string json)
    {
        try
        {
            JsonData data = JsonMapper.ToObject(json);
            if ((int)data["code"] != 0)
            {
                LogError("Json Error " + data["msg"]);
            }
        }
        catch (Exception e)
        {
            throw (e);
        }
    }

    private void BeforeStartHandler(string json)
    {
        try
        {
            JsonData data = JsonMapper.ToObject(json);
            if ((int)data["code"] != 0)
            {
                OSBridgeManager.Instance.isReturnApp = true;
                SceneManager.LoadScene("StartGame");
                //OSBridgeManager.Instance.OnUnityBack(0);
                Debug.Log("已经退出了游戏");
            }
            else
            {
                SceneManager.LoadScene(OSBridgeManager.Instance.GameName);
            }
        }
        catch (Exception e)
        {
            throw e;
        }
    }
    private void StartGameHandler(string json)
    {
        try
        {
            JsonData data = JsonMapper.ToObject(json);
            if ((int)data["code"] != 0)
            {
                LogError("Json Error " + data["msg"]);
            }
        }
        catch (Exception e)
        {
            throw (e);
        }
    }

    private IEnumerator Get(string url, AfterWWWGetHandler handler)
    {
        //Debug.Log(url);
        WWW www = new WWW(url);
        yield return www;
        JsonData data = JsonMapper.ToObject(www.text);
        if (!string.IsNullOrEmpty(www.error))
        {
            LogError("WWW error " + www.error);
        }
        else
        {
            handler(www.text);
        }
        www.Dispose();
    }

    private IEnumerator Post(string url, WWWForm form, AfterWWWPostHandler handler)
    {
        WWW www = new WWW(url, form);
        yield return www;
        if (!string.IsNullOrEmpty(www.error))
        {
            LogError("WWW error " + www.error);
        }
        else
        {
            handler(www.text);
        }
        www.Dispose();
    }

    public override void Init()
    {
        DontDestroyOnLoad(this);
    }

    private void Start()
    {
        //Test();
        //EventDispatcher.TriggerEvent("OnInitGame", _gameName);
        //InitGame(ReadyToSatrt.AppJson);
    }
    
    private void Test()
    {
        /************here write test code**************/
        GameInfo gameInfo = new GameInfo();
        gameInfo.gameID =11;//1 4 5 6 9 10 11
        gameInfo.userToken =
            "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VySWQiOjQ4LCJpYXQiOjE1MDA5NTQ0MzIsImV4cCI6MTUwMTEyNzIzMn0.YscEUMUFcqzqSyHQdP8qhzAKtXIOrduRw79CdqTn0DQ";
        
        InitGame(JsonMapper.ToJson(gameInfo));
       // EventDispatcher.TriggerEvent("OnInitGame", _gameName);
        /************here write test code**************/
    }

}
 